package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.ILoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.UserConverterMapper;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Slf4j
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserVerifyMapper userVerifyMapper;
    @Autowired
    UserConverterMapper userConverterMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest loginRequest) {
        UserLoginResponse userLoginResponse = new UserLoginResponse();

        // 1、 验证用户名以及密码
        Example memberExample = new Example(Member.class);
        memberExample.createCriteria().andEqualTo("username", loginRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(memberExample);
        //     将请求中的密码进行加密处理, 然后进行比对
        String userPassWord = DigestUtils.md5DigestAsHex(loginRequest.getPassword().getBytes());

        UserLoginResponse loginResponse = verify(members, userPassWord);
        if (!loginResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return loginResponse;
        }

        Example userVerifyExample = new Example(UserVerify.class);
        userVerifyExample.createCriteria().andEqualTo("username", loginRequest.getUserName())
                                            .andEqualTo("isVerify", "Y");


        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(userVerifyExample);
        if (CollectionUtils.isEmpty(userVerifies)) {
            userLoginResponse.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
            return userLoginResponse;
        }
        // 将该用户所有的信息都塞入到token
        Member member = members.get(0);
        String jsonString = JSONObject.toJSONString(member);
        String token = JwtTokenUtils.builder().msg(jsonString).build().creatJwtToken();
        loginResponse.setToken(token);
        return loginResponse;
    }

    @Override
    public CheckLoginResponse checkLogin(CheckLoginRequest checkLoginRequest) {
        checkLoginRequest.requestCheck();
        String userInfo = checkLoginRequest.getUserInfo();
        JSONObject jsonObject = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(jsonObject.get("id").toString());
        String username = String.valueOf(jsonObject.get("username"));
        CheckLoginResponse checkLoginResponse = new CheckLoginResponse();
        checkLoginResponse.setUid(uid);
        checkLoginResponse.setUsername(username);
        return checkLoginResponse;
    }

    // 校验用户名密码
    public UserLoginResponse verify(List<Member> members, String userPassWord) {

        UserLoginResponse userLoginResponse = new UserLoginResponse();

        if (CollectionUtils.isEmpty(members)) {
            userLoginResponse.setCode(SysRetCodeConstants.REQUEST_CHECK_FAILURE.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.REQUEST_CHECK_FAILURE.getMessage());
            return userLoginResponse;
        }
        // 判断请求参数的密码与表中存放是否一致
        Member member = members.get(0);
        if (!member.getPassword().equals(userPassWord)) {
            userLoginResponse.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
            return userLoginResponse;
        }

        // 如果前面的条件都没能够满足，那么用户名密码校验成功
        userLoginResponse = userConverterMapper.converter(member);
        userLoginResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        userLoginResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return userLoginResponse;
    }


    @Override
    public CheckAuthResponse validToken(CheckAuthRequest checkAuthRequest) {
        CheckAuthResponse checkAuthResponse = new CheckAuthResponse();
        try{
            String userInfo = JwtTokenUtils.builder().token(checkAuthRequest.getToken()).build().freeJwt();
            checkAuthResponse.setUserinfo(userInfo);
            log.info("userInfo:"+userInfo);
            checkAuthResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        }catch (ValidateException e){
            checkAuthResponse.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
        }
        return checkAuthResponse;
    }
}
